package com.caishi.lkx.user.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.caishi.lkx.user.mapper.DistributionUserMapper;
import com.caishi.lkx.user.model.DistributionUser;
import com.caishi.lkx.user.service.IDistributionUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DistributionUserServiceImpl extends ServiceImpl<DistributionUserMapper, DistributionUser> implements IDistributionUserService {
    @Resource
    private DistributionUserMapper distributionUserMapper;


    @Override
//    根据禁用的代理商id，禁用代理商以及禁用挂靠在代理商下的所有分销人员,此时无法再分销，但是分销佣金表还在，
    public Boolean disabledAgent(String agentId, Boolean deleted) {
        return distributionUserMapper.disabledAgent(agentId, deleted) > 0;
    }



    /// /    重新启用代理商后，原挂靠的的分销人员消失不可见，需重新添加(即改变delete字段)，重新添加后的分销人员展示的佣金记录金额还在
//    Boolean reEnableAgent(String agentId){
//        return false;
//    }
    @Override
    public Page<DistributionUser> getDistributionTop(Page<DistributionUser> page) {
        return distributionUserMapper.getDistributionTop(page);
    }
    public  List<DistributionUser> getDistributionUserTree( List<String> ids){
        List<DistributionUser> allUsers = distributionUserMapper.getDistributionUserTree(ids); // 查询所有用户
        return TreeUtils.buildTree(allUsers);
    }
    // 向上递归获取分销人员
    public List<DistributionUser> getRecursiveUser(String userId){
        return distributionUserMapper.getRecursiveUser(userId); // 查询所有用户
//        return TreeUtils.buildTree(allUsers);
    }
}


class TreeUtils {

    public static List<DistributionUser> buildTree(List<DistributionUser> allUsers) {
        Map<String, DistributionUser> userMap = new HashMap<>();
        List<DistributionUser> rootNodes = new ArrayList<>();

        // 第一步：将所有用户放入 map，方便查找
        for (DistributionUser user : allUsers) {
            user.setChildren(new ArrayList<>());
            userMap.put(user.getId(), user);
        }

        // 第二步：构建树
        for (DistributionUser user : allUsers) {
            String parentId = user.getParentId();

            if (parentId == null || userMap.get(parentId) == null) {
                // 如果没有父节点 或者 父节点不存在，则为根节点
                rootNodes.add(user);
            } else {
                // 否则加入对应父节点的 children 列表
                userMap.get(parentId).getChildren().add(user);
            }
        }
        return rootNodes;
    }
}
